package com.quiz.quazz.util;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.quiz.quazz.client.Player;
import com.quiz.quazz.client.PlayerList;

public class JSONHelper {

	public static JSONObject playerToJSON(Player decodedPlayer) throws JSONException {
		JSONObject playerJSON = new JSONObject();

		playerJSON.put("type", "player");
		playerJSON.put("name", decodedPlayer.getName());
		playerJSON.put("ip", decodedPlayer.getIp());
		playerJSON.put("points", decodedPlayer.getPoints());

		return playerJSON;
	}

	public static Player jsonToPlayer(JSONObject playerJSON) throws JSONException {
		Player player = new Player(playerJSON.getString("ip"), playerJSON.getString("name"));
		player.setPoints(Integer.parseInt(playerJSON.getString("points")));

		return player;
	}

	public static JSONObject playerListToJSON(PlayerList playerList) throws JSONException {
		JSONObject playerListJSON = new JSONObject();

		playerListJSON.put("type", "playerList");

		JSONArray players = new JSONArray();
		for (Player player : playerList.getPlayers()) {
			players.put(playerToJSON(player));
		}
		playerListJSON.put("players", players);

		playerListJSON.put("playerCount", playerList.getPlayerCount());

		return playerListJSON;
	}

	public static PlayerList jsonToPlayerList(JSONObject playerListJSON) throws JSONException {
		PlayerList decodedPlayerList = new PlayerList();

		JSONArray encodedPlayers = playerListJSON.getJSONArray("players");
		for (int i = 0; i < encodedPlayers.length(); i++) {
			decodedPlayerList.addPlayer(jsonToPlayer((JSONObject) encodedPlayers.get(i)));
		}

		return decodedPlayerList;
	}

	public static boolean isJSONValid(String string) {
		boolean valid = false;
		try {
			new JSONObject(string);
			valid = true;
		} catch (JSONException ex) {
			valid = false;
		}
		return valid;
	}
}
